package com.hbt.myplus.socket;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hbt.myplus.model.Chat;
import com.hbt.myplus.model.PetOwn;
import com.hbt.myplus.service.impl.PetOwnServiceImpl;
import com.hbt.myplus.service.impl.PetServiceImpl;
import lombok.Data;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @Author：JCccc
 * @Description：
 * @Date： created in 15:56 2019/5/13
 */

@Component
@ServerEndpoint(value = "/chat/{openid}")
public class ChatSocket {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static PetOwnServiceImpl petOwnService;

    @Autowired
    public void setDeviceListenerService(PetOwnServiceImpl petser) {
        ChatSocket.petOwnService = petser;
    }
//    @JsonIgnore
//    public static Map<String, Map<String, ChatSocket>> build = new ConcurrentHashMap<>();
    //用于保存socket的集合容器
    @JsonIgnore
    public static CopyOnWriteArrayList<ChatSocket> socket_list = new CopyOnWriteArrayList<ChatSocket>();
    //会话
    @JsonIgnore
    public Session session;

    private String openid;

    private boolean isDoc = true;

    public boolean isDoc() {
        return isDoc;
    }

    public void setDoc(boolean doc) {
        isDoc = doc;
    }

    @OnOpen
    public void onOpen(@PathParam("openid") String openid, Session session) throws Exception {
        synchronized (ChatSocket.class){
            try {
                Integer.parseInt(openid);
            }catch (Exception e){
                setDoc(false);
            }

            socket_list.forEach(socket -> {
                JSONObject object = new JSONObject();
                object.put("type", "link");
                socket.session.getAsyncRemote().sendText(object.toString());
            });


            logger.info("有socket 连接："+openid);
            this.session = session;
            this.openid = openid;
            List<ChatSocket> list = socket_list.stream().filter(a -> a.openid.equals(openid)).collect(Collectors.toList());
            ChatSocket socket = list != null && list.size()>0?list.get(0): null;
            if (socket !=null){
                socket.session.close();
                socket_list.remove(socket);
                socket_list.add(this);
            }else {
                socket_list.add(this);
            }
        }//synchronized end
    }//onOpen end



    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("服务端发生了错误"+error.getMessage());
        System.out.println(" socket 发生 error:"+error.getMessage());
        logger.error("有socket error：");
        socket_list.remove(this);
        //error.printStackTrace();
    }
    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() throws IOException {
        logger.info("服务端发生了close");
        socket_list.remove(this);
    }//onClose end

    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        logger.info(" socket 发生 onMessage: "+message);
        JSONObject jsonObject = JSONObject.fromObject(message);
        jsonObject.put("type", "chat");
        jsonObject.put("time", format.format(new Date()));

        Chat chat = new Chat();
        chat.setDid(jsonObject.getInt("did"));
        chat.setContent(jsonObject.getString("content"));
        chat.setPoid(jsonObject.getString("poid"));
        String poid = jsonObject.getString("poid");
        if(!StringUtils.isEmpty(poid)){
            PetOwn petOwn = petOwnService.getOne(new QueryWrapper<PetOwn>().eq("openid", openid));
            jsonObject.put("avatar", petOwn == null? "":petOwn.getAvatar());
        }
        message = jsonObject.toString();
        for(ChatSocket socket: socket_list){
            if (socket.getOpenid().equals(chat.getPoid())||socket.getOpenid().equals(chat.getDid().toString())){
                socket.session.getAsyncRemote().sendText(message);
                logger.info("发送信息给:"+socket.getOpenid());
            }
        }
    }//onMessage end


    public void sendMessageTo(String message, String TouserId) throws IOException {
    }

    public void sendMessageAll(String message,String FromuserId) throws IOException {
    }


    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

}
